package com.itheima.excel;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.commons.math3.Field;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima
 */
public class ExcelDemo {
    public static void main(String[] args) {
        //read();
        write();
    }
    public static void write(){
        //定义一个List集合, 里面封装5个用户(User)对象
        List<User> dataList = new ArrayList<>();
        dataList.add(new User(1, "张三", "男", "13309091234", "13309091234@163.com", LocalDate.of(1990, 9, 12)));
        dataList.add(new User(2, "李四", "男", "13309091235", "13309091235@163.com", LocalDate.of(1990, 8, 11)));
        dataList.add(new User(3, "王五", "男", "13309091236", "13309091236@163.com", LocalDate.of(1990, 7, 10)));
        dataList.add(new User(4, "赵六", "女", "13309091237", "13309091237@163.com", LocalDate.of(1990, 6, 9)));
        dataList.add(new User(5, "田七", "男", "13309091238", "13309091238@163.com", LocalDate.of(1990, 5, 8)));

        // 单元格的格式化
        WriteCellStyle writeCellStyle = new WriteCellStyle();
        // 样式水平居中
        writeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        EasyExcel.write(new File("d:\\stu.xlsx")).head(User.class)
            .registerWriteHandler(new HorizontalCellStyleStrategy(null, writeCellStyle))
            .sheet("我的表格")
            .doWrite(dataList);

    }

    public static void read(){
        File file = new File("D:\\work\\sz151\\下发资料\\web\\【扩展】excel导入导出\\资料\\03. excel文件\\用户信息.xlsx");
        EasyExcel.read(file, User.class, new ReadListener<User>() {
            @Override
            public void invoke(User user, AnalysisContext analysisContext) {
                System.out.println(JSONUtil.toJsonStr(user));
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                System.out.println("读取完毕");
            }
        }).sheet().doRead();
    }
}
